﻿using AutoMapper;
using MediatR;
using PublicClass;
using S.Breeding.Domain;
using S.Breeding.Infrastructure;
using S.Breeding.Read.Api.Application.Command.LambWeaningCommand;

namespace S.Breeding.Read.Api.Application.CommandHandlers.LambWeaningCoommandHandlers
{
    public class LambWeaningListCommandHandlers : IRequestHandler<LambWeaningListCommand,PageInfo<LambWeaning>>
    {
        private readonly IRepository<LambWeaning> repository;
        private readonly IMapper mapper;
        private readonly PageInfo<LambWeaning> pageInfo;
        public LambWeaningListCommandHandlers(IRepository<LambWeaning> repository, IMapper mapper,PageInfo<LambWeaning> pageInfo)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.pageInfo = pageInfo;
        }

        public async Task<PageInfo<LambWeaning>> Handle(LambWeaningListCommand request, CancellationToken cancellationToken)
        {
            var list = repository.All().Result;
            //羔羊
            if (!string.IsNullOrEmpty(request.LambOverbit))
            {
                list = list.Where(x => x.LambOverbit == request.LambOverbit);
            }
            //种母
            if (!string.IsNullOrEmpty(request.MomEarbugles))
            {
                list = list.Where(x => x.MomEarbugles == request.MomEarbugles);
            }
            //断奶日期 区间查询
            if (request.Sdate != null)
            {
                list = list.Where(x => x.WeaningDate >= request.Sdate);
            }
            if (request.Edate != null)
            {
                list = list.Where(x => x.WeaningDate <= request.Edate);
            }
            //称重日龄 区间查询
            if (request.SWeaningDay > 0)
            {
                list = list.Where(x => x.WeaningDay >= request.SWeaningDay);
            }
            if (request.EWeaningDay > 0)
            {
                list = list.Where(x => x.WeaningDay <= request.EWeaningDay);
            }
            //断奶重 区间查询
            if (request.SWeaningWeight > 0)
            {
                list = list.Where(x => x.WeaningWeight >= request.SWeaningWeight);
            }
            if (request.EWeaningWeight > 0)
            {
                list = list.Where(x => x.WeaningWeight <= request.EWeaningWeight);
            }
            pageInfo.totalCount = list.Count();
            pageInfo.pageCount = (int)Math.Ceiling(pageInfo.totalCount * 1.0 / request.pageSize);
            list = list.OrderByDescending(x => x.WeaningDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            return new PageInfo<LambWeaning>
            {
                datas = list.ToList(),
                totalCount = pageInfo.totalCount,
                pageCount = pageInfo.pageCount,
            };
        }
    }
}
